package com.ruoyi.system.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author lixbin
 * @ClassName PdfUtil
 * @datetime 2023年 08月 05日 23:07
 * @version: 1.0
 */
public class PdfUtil {
    public static void createPdfFromImg(String img, File pdfFile) throws Exception {
        Image image = Image.getInstance(img);
        createPdfFromImg(image, pdfFile);
    }

    public static void createPdfFromImg(byte[] img, File pdfFile) throws Exception {
        Image image = Image.getInstance(img);
        createPdfFromImg(image, pdfFile);
    }

    public static void createPdfFromImg(Image image, File pdfFile) throws Exception {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            document.open();
//        image.setAbsolutePosition(0, document.getPageSize().getHeight() - image.getHeight());
//        image.setAlignment(Image.MIDDLE);
            image.setAlignment(Image.ALIGN_BASELINE);
            image.scaleToFit(document.getPageSize().getWidth(), document.getPageSize().getHeight());
            document.add(image);
        } finally {
            document.close();
        }
    }

    public static void main(String[] args) throws Exception {
        File pdf = new File("d:/4.pdf");
        createPdfFromImg("d:/a2.png", pdf);
    }
}
